import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:video_player/video_player.dart';
import 'package:videodemo/z_video/assembly/zsn_bar.dart';
import 'package:videodemo/z_video/assembly/zsn_header.dart';
import 'package:videodemo/z_video/assembly/zsn_pause.dart';
import 'package:videodemo/z_video/assembly/zsn_progess.dart';
import 'package:videodemo/z_video/zsn_class.dart';
import 'package:videodemo/z_video/zsn_fullScreen.dart';
import 'package:videodemo/z_video/zsn_providers.dart';

class ZsnVideo extends StatefulWidget {
  final double height;
  final String videoUrl;
  final String title;
  const ZsnVideo(
      {super.key, required this.videoUrl, this.height = 220, this.title = ''});

  @override
  State<ZsnVideo> createState() => _VideoBaseState();
}

class _VideoBaseState extends State<ZsnVideo> {
  late VideoPlayerController _videoController;

  Timer? timer; // 创建个延时器
  ZsnProviders zProvider = ZsnProviders(); // 获取provider

  void playVideo() {
    zProvider.changePause();
    if (zProvider.pause) {
      _videoController.pause();
    } else {
      _videoController.play();
    }
  }

  // 控制亮度（模拟）
  void _controlBrightness(double delta) {
    double newBrightness = zProvider.currentBrightness + delta;
    newBrightness = newBrightness.clamp(0.0, 1.0); // 亮度限制在 0-1
    zProvider.setBrightness(newBrightness);
    ZsnClass().setApplicationBrightness(newBrightness);
  }

  // 控制音量
  void _controlVolume(double delta) {
    double newVolume = zProvider.currentVolume + delta;
    newVolume = newVolume.clamp(0.0, 1.0); // 音量限制在 0-1
    zProvider.setVolume(newVolume);
    _videoController.setVolume(newVolume);
  }

  void initializeVideo(String videoUrl) async {
    try {
      // 判断是否已经初始化过
      if (zProvider.videoInitialized) {
        _videoController.dispose();
        _videoController.removeListener(() {}); // 移除监听器
        zProvider.videoInitialized = false;
      }

      _videoController = VideoPlayerController.networkUrl(Uri.parse(videoUrl));
      // 获取重定向后的视频链接
      // final redirectedUrl = await getRedirectedVideoUrl(videoUrl);
      // _videoController =
      //     VideoPlayerController.networkUrl(Uri.parse(redirectedUrl));
      _videoController.setVolume(zProvider.currentVolume);
      await _videoController.initialize();
      await _videoController.play();
      await _videoController.setLooping(true);

      _videoController.setVolume(zProvider.currentVolume);
      zProvider.setPause(false);
      zProvider.resetState();
      zProvider.setVideoDuration(_videoController.value.duration);
      zProvider.videoInitialized = true;

      // 实时监听视频播放进度
      _videoController.addListener(() {
        // 调整视频进度时，没有预加载的视频会重新加载，如何监听视频重新加载和加载完成
        if (_videoController.value.isBuffering) {
          zProvider.setBuffering(true);
        } else if (_videoController.value.isInitialized) {
          zProvider.setBuffering(false);
        }
        zProvider.setVideoCurrentDuration(_videoController.value.position);
      });
    } catch (e) {
      print('视频初始化失败: $e');
      zProvider.setErrorMessage('Failed to load video!'); // 设置错误信息
    }
  }

  void onTap() {
    // 点击时显示或隐藏控制栏
    zProvider.changeShowUI();
    timer?.cancel();
    timer = Timer(Duration(milliseconds: 5000), () {
      zProvider.setShowUI(false);
    });
  }

  void onDoubleTap() {
    // 双击时暂停或播放视频
    zProvider.changePause();
    if (zProvider.pause) {
      _videoController.pause();
    } else {
      _videoController.play();
    }
  }

  // 长按开始 和 结束
  void onLongPress() {
    if (zProvider.isLock) return;
    // 长按改变视频倍速
    _videoController.setPlaybackSpeed(3.0);
  }

  void onLongPressEnd(details) {
    if (zProvider.isLock) return;
    // 长按结束时取消视频倍速改变
    _videoController.setPlaybackSpeed(1.0);
  }

  // 垂直滑动开始 和 结束
  void onVerticalDragUpdate(details) {
    if (zProvider.isLock) return;
    // 判断是否是上下滑动
    if (details.delta.dy.abs() > details.delta.dx.abs()) {
      final double screenWidth = MediaQuery.of(context).size.width;
      double positionX = details.localPosition.dx;
      if (positionX < screenWidth / 2) {
        // 手势在左侧 控制视频亮度 保留小数点后一位
        zProvider.setBrightnessUI(true);
        _controlBrightness(-details.delta.dy / 100);
      } else {
        // 手势在右侧 控制视频音量
        zProvider.setVolumeUI(true);
        _controlVolume(-details.delta.dy / 100);
      }
    }
  }

  void onVerticalDragEnd(details) {
    if (zProvider.isLock) return;
    zProvider.setBrightnessUI(false);
    zProvider.setVolumeUI(false);
  }

  // 水平滑动开始 和 结束
  void onHorizontalDragUpdate(details) {
    if (zProvider.isLock) return;
    if (details.delta.dx.abs() > details.delta.dy.abs()) {
      if (zProvider.beforeProgress == Duration.zero) {
        zProvider.setBeforeProgress(zProvider.videoCurrentDuration);
      }
      zProvider.setSecond(details.delta.dx);
      zProvider.calculateAfterProgress();
    }
  }

  void onHorizontalDragEnd(details) {
    if (zProvider.isLock) return;
    _videoController.seekTo(zProvider.afterProgress);
    zProvider.setBeforeProgress(Duration.zero);
    zProvider.setAfterProgress(Duration.zero);
    zProvider.resetSecond();
  }

  @override
  void initState() {
    super.initState();
    _videoController = VideoPlayerController.networkUrl(
      Uri.parse(widget.videoUrl),
    );
    initializeVideo(widget.videoUrl);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    zProvider = Provider.of<ZsnProviders>(context, listen: false);
  }

  @override
  void didUpdateWidget(ZsnVideo oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 比较旧的 videoUrl 和新的 videoUrl
    if (oldWidget.videoUrl != widget.videoUrl) {
      zProvider.errorMessage = null;
      zProvider.videoDuration = const Duration();
      zProvider.videoCurrentDuration = const Duration();
      // 重新初始化视频
      initializeVideo(widget.videoUrl);
    }
  }

  @override
  void dispose() {
    _videoController.dispose();
    _videoController.removeListener(() {}); // 移除监听器
    ZsnClass().resetApplicationBrightness(); // 重置应用亮度
    super.dispose();
    if (timer != null) timer!.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ZsnProviders>(
      builder: (context, provider, child) {
        return GestureDetector(
          onVerticalDragUpdate: onVerticalDragUpdate,
          onVerticalDragEnd: onVerticalDragEnd,
          onHorizontalDragUpdate: onHorizontalDragUpdate,
          onHorizontalDragEnd: onHorizontalDragEnd,
          onTap: onTap,
          onDoubleTap: onDoubleTap,
          onLongPress: onLongPress,
          onLongPressEnd: onLongPressEnd,
          child: Container(
            color: Colors.black,
            height: widget.height,
            child: Stack(
              children: [
                // 视频播放器
                Center(
                  child: provider.videoInitialized
                      ? Hero(
                          tag: 'player',
                          child: AspectRatio(
                            aspectRatio: _videoController.value.aspectRatio,
                            child: VideoPlayer(_videoController),
                          ))
                      : provider.errorMessage != null
                          ? Icon(
                              Icons.videocam_off_sharp,
                              color: Colors.red,
                              size: 45,
                            )
                          : CircularProgressIndicator(),
                ),
                // 顶部 UI
                if (provider.showUI && !provider.isLock)
                  ZsnHeader(
                    title: widget.title,
                  ),
                // 暂停 UI
                if (provider.pause)
                  Center(
                      child: IconButton(
                          onPressed: playVideo,
                          icon: Icon(
                            Icons.play_arrow,
                            color: ZsnClass().baseColor,
                            size: 45,
                          ))),
                // 缓冲 UI
                if (provider.isBuffering)
                  Center(
                      child: CircularProgressIndicator(
                    backgroundColor: Colors.transparent,
                  )),
                // 快进快退 UI
                if (provider.second != 0)
                  Stack(
                    alignment: Alignment.center, // 这会将 Stack 的子内容居中
                    children: [
                      Positioned(
                        top: 40, // 垂直居中
                        child: Container(
                          // ignore: deprecated_member_use
                          color: Colors.black.withOpacity(0.2),
                          padding: EdgeInsets.symmetric(
                              horizontal: 10), // 可选，调整文字与容器边距
                          child: Text(
                            '${ZsnClass().formatDuration(provider.afterProgress)}/${ZsnClass().formatDuration(provider.videoDuration)}',
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                            ),
                            textAlign: TextAlign.center, // 确保文字居中
                          ),
                        ),
                      ),
                    ],
                  ),
                // 音量 UI
                if (provider.volumeUI)
                  ZsnBar(height: widget.height, value: provider.currentVolume),
                // 亮度 UI
                if (provider.brightnessUI)
                  ZsnBar(
                    height: widget.height,
                    value: provider.currentBrightness,
                    isVolume: false,
                  ),
                // 底部控制条 UI
                if (provider.showUI && !provider.isLock)
                  Positioned(
                      bottom: 0,
                      left: 0,
                      child: Container(
                        padding: EdgeInsets.all(5),
                        width: MediaQuery.of(context).size.width,
                        // ignore: deprecated_member_use
                        color: Colors.black.withOpacity(0.1),
                        child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            // 上下居中
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              //  播放暂停按钮
                              ZsnPause(
                                  pause: provider.pause, playVideo: playVideo),
                              // 播放进度
                              Text(
                                ZsnClass().formatDuration(
                                    provider.videoCurrentDuration),
                                style: TextStyle(color: Colors.white),
                              ),
                              SizedBox(
                                width: 10,
                              ),
                              // 进度条
                              ZsnProgess(controller: _videoController),
                              SizedBox(
                                width: 10,
                              ),
                              // 播放进度
                              Text(
                                ZsnClass()
                                    .formatDuration(provider.videoDuration),
                                style: TextStyle(color: Colors.white),
                              ),
                              // 全屏按钮
                              IconButton(
                                icon: Icon(
                                  Icons.fullscreen,
                                  color: Colors.white,
                                ),
                                onPressed: () {
                                  Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) => ZsnFullscreen(
                                                title: widget.title,
                                                providers: provider,
                                                controller: _videoController,
                                                onTap: onTap,
                                                onDoubleTap: onDoubleTap,
                                                onLongPress: onLongPress,
                                                playVideo: playVideo,
                                                onVerticalDragUpdate:
                                                    onVerticalDragUpdate,
                                                onVerticalDragEnd:
                                                    onVerticalDragEnd,
                                                onHorizontalDragUpdate:
                                                    onHorizontalDragUpdate,
                                                onHorizontalDragEnd:
                                                    onHorizontalDragEnd,
                                                onLongPressEnd: onLongPressEnd,
                                              )));
                                },
                              ),
                            ]),
                      )),
                // 锁屏按钮
                if (provider.showUI)
                  Positioned(
                      top: widget.height / 2 - 25,
                      left: 10,
                      child: IconButton(
                          style: ButtonStyle(
                            backgroundColor: WidgetStateProperty.all(
                                const Color.fromARGB(68, 158, 158, 158)),
                          ),
                          onPressed: () {
                            provider.changeLock();
                          },
                          icon: Icon(
                            provider.isLock ? Icons.lock : Icons.lock_open,
                            color: Colors.white,
                            size: 25,
                          ))),
              ],
            ),
          ),
        );
      },
    );
  }
}

Future<String> getRedirectedVideoUrl(String initialUrl) async {
  final response = await Dio().head(initialUrl);
  return response.requestOptions.uri.toString();
}
